package com.xzs.thinking.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author : Iris.Xiao
 * @date : 2017/11/22 11:42
 * @description :
 */
@Configuration
@MapperScan(basePackages = {"com.xzs.thinking.dao.mapper.uat"}, sqlSessionFactoryRef = "sqlSessionFactoryUAT")
public class MapperDataSourceUAT {
    @Autowired
    @Qualifier(value="secondaryDataSource")
    private DataSource uatSource;

    @Bean
    public SqlSessionFactory sqlSessionFactoryUAT() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(uatSource);
        factoryBean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath:mapper/*.xml")
        );
        return factoryBean.getObject();

    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplateUAT() throws Exception {
        //使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryUAT());
        return template;
    }

    @Bean(name = "transactionManagerUAT")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("secondaryDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
